import React, { useState, useEffect } from 'react';
import { Row, Col, Card, List, Typography, Empty } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { Category, Product } from '../../types';
import { mockCategories, mockProducts } from '../../services/mockData';
import { SearchService } from '../../services/searchService';

const { Title } = Typography;

const CategoryPage: React.FC = () => {
  const [categories, setCategories] = useState<Category[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [products, setProducts] = useState<Product[]>([]);
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    setCategories(mockCategories);
    
    // 检查是否有搜索结果传递
    const searchResults = location.state?.searchResults;
    const keyword = location.state?.keyword;
    
    if (searchResults) {
      setProducts(searchResults);
      setSelectedCategory('');
    } else {
      setProducts(mockProducts);
    }
  }, [location.state]);

  const handleCategorySelect = (categoryId: string) => {
    setSelectedCategory(categoryId);
    if (categoryId) {
      const filteredProducts = SearchService.getProductsByCategory(categoryId);
      setProducts(filteredProducts);
    } else {
      setProducts(mockProducts);
    }
  };

  const handleProductClick = (productId: string) => {
    navigate(`/product/${productId}`);
  };

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto' }}>
      <Row gutter={16}>
        {/* 分类侧边栏 */}
        <Col xs={24} sm={6} md={6}>
          <Card title="商品分类" style={{ marginBottom: 16 }}>
            <List
              dataSource={[{ id: '', name: '全部商品', icon: '📋' }, ...categories]}
              renderItem={(category) => (
                <List.Item
                  onClick={() => handleCategorySelect(category.id)}
                  style={{
                    cursor: 'pointer',
                    background: selectedCategory === category.id ? '#f0f0f0' : 'transparent',
                    padding: '12px',
                    borderRadius: 4
                  }}
                >
                  <span style={{ fontSize: 16 }}>
                    {category.icon} {category.name}
                  </span>
                </List.Item>
              )}
            />
          </Card>
        </Col>

        {/* 商品列表 */}
        <Col xs={24} sm={18} md={18}>
          <div style={{ marginBottom: 16 }}>
            <Title level={3}>
              {selectedCategory ? 
                categories.find(c => c.id === selectedCategory)?.name || '商品列表' : 
                '全部商品'
              }
            </Title>
          </div>

          {products.length > 0 ? (
            <Row gutter={[16, 16]}>
              {products.map((product) => (
                <Col xs={12} sm={12} md={8} lg={6} key={product.id}>
                  <Card
                    hoverable
                    className="product-card"
                    cover={
                      <img
                        alt={product.name}
                        src={product.image}
                        style={{ height: 200, objectFit: 'cover' }}
                      />
                    }
                    onClick={() => handleProductClick(product.id)}
                  >
                    <Card.Meta
                      title={product.name}
                      description={
                        <div>
                          <div style={{ marginBottom: 8 }}>
                            <span className="price-current">¥{product.price}</span>
                            {product.originalPrice && (
                              <span className="price-original">¥{product.originalPrice}</span>
                            )}
                          </div>
                          <div>库存: {product.stock}</div>
                        </div>
                      }
                    />
                  </Card>
                </Col>
              ))}
            </Row>
          ) : (
            <Empty description="暂无商品" />
          )}
        </Col>
      </Row>
    </div>
  );
};

export default CategoryPage;
